package com.five.admin.server.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.five.admin.mapper.CategoryMapper;
import com.five.admin.server.CategoryService;
import com.five.admin.server.ProductService;
import com.five.pojo.entity.Category;
import com.five.pojo.vo.CategoryTreeVo;
import com.five.pojo.vo.MobileProductListVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private ProductService productService;

    @Override
    public List<CategoryTreeVo> queryCategoryTree() {
        List<Category> list = getBaseMapper().queryAll();
        return list.stream().filter(item -> item.getParentId() == 0)
                .map(item -> {
                    return CategoryTreeVo.builder()
                            .id(item.getId())
                            .name(item.getCategoryName())
                            .children(list.stream()
                                    .filter(child -> child.getParentId() != 0)
                                    .filter(child -> child.getParentId().equals(item.getId()))
                                    .map(child -> {
                                        return CategoryTreeVo.builder()
                                                .id(child.getId())
                                                .name(child.getCategoryName())
                                                .parentId(item.getId())
                                                .build();
                                    }).collect(Collectors.toList())).build();
                }).collect(Collectors.toList());
    }

    @Override
    public boolean deleteCategory(Long id) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        //查询子类
        List<Category> list = getBaseMapper().selectList(queryWrapper);
        if (list.size() == 0) {
            //查询分类下面的产品
            List<MobileProductListVo> listVos = productService.queryProductByCategoryId(id);
            if (listVos.size() == 0) {
                return getBaseMapper().deleteById(id) > 0;
            }
        }
        return false;
    }

    @Override
    public String deleteCategoryBatch(List<Long> ids) {
        StringBuilder builder = new StringBuilder();
        builder.append("id:");
        for (Long id : ids) {
            if (!deleteCategory(id)) {
                builder.append(id).append(id+",");
            }
        }

        return builder.toString();
    }
}
